/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.cxhd.dc.tool;

import com.cxhd.dc.DataConfig;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.dicom4j.dicom.DicomException;
import org.dicom4j.dicom.DicomTags;
import org.dicom4j.io.media.DicomFile;

/**
 *
 * @author Administrator
 */
public class FileUtil {

    /*
     *
     获取文件夹下所有的文件
     */
    public static List<File> getFile(String path, boolean filter, String endwith) {
        List<File> list = new ArrayList<File>();
        File[] f = new File(path).listFiles();
        System.out.println(f.length + "------------------");
        if (f != null) {
            for (File fs : f) {
                if (fs.isDirectory()) {
                    //System.out.println(fs.getName());
                    getFile(fs.getAbsolutePath(), list, filter, endwith);
                } else if (filter) {
                    System.out.println(fs.getName() + "  " + endwith);
                    if (fs.getName().endsWith(endwith) && fs.canWrite()) {
                        list.add(fs);
                    } else if (fs.canWrite()) {
                        fs.delete();
                    }
                } else {
                    list.add(fs);
                }

            }
            return list;
        }
        return null;
    }

    private static void getFile(String path, List<File> list, boolean filter, String endwith) {
        File[] f = new File(path).listFiles();
        for (File fs : f) {
            if (fs.isDirectory()) {
                getFile(fs.getAbsolutePath(), list, filter, endwith);
            } else if (filter) {
                if (fs.getName().endsWith(endwith)) {
                    list.add(fs);
                }
            } else {
                list.add(fs);
            }

        }
    }

    public static long forTransfer(File f1, File f2) throws Exception {
        long time = new Date().getTime();
        int length = 2097152;
        FileInputStream in = new FileInputStream(f1);
        FileOutputStream out = new FileOutputStream(f2);
        FileChannel inC = in.getChannel();
        FileChannel outC = out.getChannel();
        int i = 0;
        while (true) {
            if (inC.position() == inC.size()) {
                inC.close();
                outC.close();
                return new Date().getTime() - time;
            }
            if ((inC.size() - inC.position()) < 20971520) {
                length = (int) (inC.size() - inC.position());
            } else {
                length = 20971520;
            }
            inC.transferTo(inC.position(), length, outC);
            inC.position(inC.position() + length);
            i++;
        }
    }

    public static long copyFile(File f1, File f2) {
        FileInputStream in = null;
        try {
            long time = new Date().getTime();
            int length = 2097152;
            in = new FileInputStream(f1);
            FileOutputStream out = new FileOutputStream(f2);
            byte[] buffer = new byte[length];
            while (true) {
                int ins = in.read(buffer);
                if (ins == -1) {
                    in.close();
                    out.flush();
                    out.close();
                    return new Date().getTime() - time;
                } else {
                    out.write(buffer, 0, ins);
                }
            }
        } catch (Exception ex) {

        } finally {
            try {
                in.close();
            } catch (IOException ex) {
                Logger.getLogger(FileUtil.class.getName()).log(Level.SEVERE, null, ex);
            }
        }
        return 0;
    }

    public static void writeText(String name, String Content) {
        try {
            /*
             * FileWriter outFile=new FileWriter(name); PrintWriter ox=new
             * PrintWriter(outFile); ox.print(Content); ox.close();
             * outFile.close();
             */
            OutputStreamWriter outputStream = new OutputStreamWriter(new FileOutputStream(name), "UTF-8");
            //outputStream.write("I am here");
            outputStream.write(Content);
            outputStream.close();
        } catch (IOException ex) {
        }
    }

    public static String outWriter(String name) {
        String huge = "";
        try {
            InputStreamReader inputStreamReader = new InputStreamReader(new FileInputStream(name), "UTF-8");
            BufferedReader in = new BufferedReader(inputStreamReader);

            for (;;) {
                String data = in.readLine();
//                if (!data.contains(eol)){
//                    data+=eol;
//                }
                if (data == null) {
                    break;
                } else {
                    huge += data;
                }
            }
            in.close();
            inputStreamReader.close();
        } catch (FileNotFoundException e) {
        } catch (IOException e) {
        }
        return huge;
    }

    public static boolean testPacs(String ip, int port) {
        Socket s = null;
        try {
            s = new Socket(ip, port);
            if (s.isConnected()) {
                return true;
            } else {
                return false;
            }
        } catch (UnknownHostException ex) {
            // ex.printStackTrace();
            System.out.println("cannot connect to " + ip + ":" + port);
            return false;
        } catch (IOException ex) {
            // ex.printStackTrace();
            System.out.println("cannot connect to " + ip + ":" + port);
            return false;
        } finally {
            if (s != null) {
                try {
                    s.close();
                } catch (IOException ex) {
                    // ex.printStackTrace();
                }
            }
        }
    }

    public static String getSNtoHospitalName(String sn) {
        try {
            File color = new File("k:/reports/jsp/color.js");
            Gson gson = new Gson();
            if (color.exists()) {
                String allData = outWriter(color.getAbsolutePath());

                if (allData != null) {
                    Map<String, Object> map = gson.fromJson(allData.replace("var colorjs=", ""), new TypeToken<Map<String, Object>>() {
                    }.getType());

                    List list = (ArrayList) map.get("hospital_name");
                    for (Object o : list) {
                        Map<String, Object> mapHospital = (Map) o;
                        List<String> hospitalName = (ArrayList) mapHospital.get("name");
                        for (String name : hospitalName) {
                            if (sn.equalsIgnoreCase(name)) {
                                return mapHospital.get("display").toString();
                            }
                        }
                    }
                }
            }
        } catch (Exception e) {

        }

        return sn;
    }

    public static String makePSWD(String content) {
        try {
            MessageDigest digest = MessageDigest.getInstance("MD5");
            digest.update(content.getBytes());
            byte[] b = digest.digest();
            int i;
            StringBuilder buf = new StringBuilder("");
            for (int offset = 0; offset < b.length; offset++) {
                i = b[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            return buf.toString().substring(8, 24); //16位
            //return buf.toString(); //32位
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void sendOther(String filePath) {

        try {

            String target = DataConfig.getInstance().getSN();
            File f = new File(filePath);
            System.out.println(f.getAbsolutePath() + "" + f.exists());
            if (f.isFile()) {
                String zipName = target + "_" + f.getName() + "_" + DataConfig.getInstance().getLocalhostSN() + ".u";

                String zipPath = DataConfig.getInstance().getBasePath() + "/" + DataConfig.getInstance().getZipFolder() + zipName;
                String password = FileUtil.makePSWD(zipName.substring(0, zipName.lastIndexOf(".")));
                ZipFileTool.upZipFile(f, zipPath, password, true, zipPath);

            } else {
                System.out.println("不是文件类型");

            }
        } catch (Exception e) {

            e.printStackTrace();

        }
    }
    
     public static String getOldPatientId(String path) {
        DicomFile ldcm = new DicomFile(path);
        try {
            ldcm.open();
            return ldcm.getDataset().getElement(DicomTags.PatientID).getSingleStringValue();
        } catch (Exception ex) {
            return null;
        } finally {
            try {
                ldcm.close();
            } catch (IOException ex) {
                ex.printStackTrace();

            } catch (DicomException ex) {
                ex.printStackTrace();
            }
        }

    }
      public static String getSopiuid(String path) {
        DicomFile ldcm = new DicomFile(path);
        try {
            ldcm.open();
            return ldcm.getDataset().getElement(DicomTags.SOPInstanceUID).getSingleStringValue();
        } catch (Exception ex) {
            return null;
        } finally {
            try {
                ldcm.close();
            } catch (IOException ex) {
                ex.printStackTrace();

            } catch (DicomException ex) {
                ex.printStackTrace();
            }
        }

    }

}
